import { ref, onMounted, watch, computed } from "vue"
import type { UserInfo } from "@/interface/UserInfo"
import type { Form } from "@/interface/formData";
import axios from "axios"
import { useUserStore } from "@/stores/userStore"
import { ElMessage } from "element-plus";
import timeFormat from "@/tool/format/timeFormat";

export default function useOwnPerson() {

      const userStore = useUserStore();

      const jobApplications = ref<Form[]>();//记录所有申请的工作
      // const salaryRecords = ref<any[]>();//记录所有工作的工资

      // 当前登录学生信息
      const student = ref<UserInfo>({
            id: 0,
            indetifier: 0,
            username: "",
            password: "",
            tel: "",
            role: "",
            status: "",
            email: "",
            school: "",
            isPoor: 0,
            poorFile: "",
            createdTime: "",
            updateTiem: "",
      })


      async function REQ_getCurrentStudent() {
            await axios.get(`/api/student/ownInfo/${userStore.useridentityfer}`)
                  .then(response => {
                        student.value = response.data.data;
                  })
                  .catch(error => {
                        ElMessage.warning("后端数据获取失败");
                  })
      }

      const isLoading = ref(true);

      async function REQ_getMyJob() {
            isLoading.value = true;
            try {
                  const res = await axios.get(`/api/student/ownJob/${userStore.useridentityfer}`);
                  jobApplications.value = res.data.data;
                  console.log("fasdfa::", jobApplications.value);
            } catch (error) {
                  ElMessage.warning("后端数据获取失败");
            } finally {
                  isLoading.value = false;
            }
      }


      function updateJobApplications() {
            jobApplications.value?.forEach(item => {
                  if (item.status === "1") {
                        item.status = "待审核"
                  }
                  if (item.status === "2") {
                        item.status = "通过"
                  }
                  if (item.status === "3") {
                        item.status = "驳回"
                  }
            })
      }


      // 假设你在 jobApplications 加载后生成 salaryRecords
      const salaryRecords = computed(() => {

            if (!jobApplications.value) return []
            return jobApplications.value.map(job => ({

                  job: job.title,
                  month: new Date(job.publishTime).toISOString().split("T")[0],
                  amount:
                        (Number(job.salary) ?? 0) *
                        (((new Date(job.endTime).getDate() - new Date(job.startTime).getDate()) || 0) + 1) *
                        8,
            }))
      })

      // 当前激活的 Tab
      const activeTab = ref("jobs");



      const dialogVisible = ref(false);

      // 编辑表单副本（避免直接改 student）
      const editForm = ref({
            username: "",
            tel: "",
            school: "",
            email: "",
            password:"",
      });

      const editInfo = () => {
            // 拷贝当前 student 数据
            editForm.value = {
                  username: student.value.username,
                  tel: student.value.tel,
                  school: student.value.school,
                  email: student.value.email,
                  password:student.value.password,
            };
            dialogVisible.value = true;
      };

      const submitEdit = async () => {
            try {
                  const updated = {
                        ...student.value,
                        username: editForm.value.username,
                        tel: editForm.value.tel,
                        school: editForm.value.school,
                        email: editForm.value.email,
                        password: editForm.value.password,
                  };

                  const res = await axios.put(`/api/student/updateOwnInfo`, updated);
                  if (res.data.code === 200) {
                        ElMessage.success("修改成功");
                        student.value = updated;
                        dialogVisible.value = false;
                  } else {
                        ElMessage.error("修改失败");
                  }
            } catch (err) {
                  console.error(err);
                  ElMessage.error("请求失败");
            }
      };






      // 页面挂载时拉取学生信息
      onMounted(async () => {
            try {
                  await REQ_getCurrentStudent();
                  await REQ_getMyJob();
                  updateJobApplications();
            } catch (error) {
                  console.error("获取学生信息失败", error)
            }
      })




      return {
            student,
            jobApplications,
            salaryRecords,
            activeTab,
            isLoading,

            editForm,
            dialogVisible,
            submitEdit,
            editInfo,
      }
}
